# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from appBlog.forms import *
from rest_framework.views import APIView
from .serializers import PoemSerilizer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from . import signals

# Create your views here.

def index(request):
	poems = Poem.objects.all()
	res = 'hi,friend! wherr are you from'
	from_source = request.session.get('from_source','unkown')
	res = 'hi,friend! you come from {}'.format(from_source)
	signals.signalfoo.send(sender=None,foo1='test')
	# signals.signalfoo.disconnect(signals.signal_callback1)
	return render(request,'index.html',locals())

def disconnect_signal(request):
	signals.signalfoo.disconnect(signals.signal_callback1)
	return render(request, 'index.html', locals())

def add_poem(request):
	if request.method == 'POST':
		poem_form = PoemForm(request.POST)
		if poem_form.is_valid():
			poem_form.save()
			return HttpResponse('添加诗歌成功')
	else:
		poem_form = PoemForm()
	return render(request,'add_poem.html',locals())

def add_todo(request):
	if request.method == 'POST':
		todo_form = ToDoForm(request.POST)
		if todo_form.is_valid():
			todo_form.save()
			return HttpResponse('添加todo成功')
	else:
		todo_form = ToDoForm()
	return render(request, 'add_todo.html',locals())

def todo_list(request):
	signals.signalfoo.send(sender=None, foo1='test')
	return render(request,'todo_list.html',{'showType':'所有列表','todo_list':ToDo.objects.all()})

class PoemListView(APIView):
	def get(self,request,format=None):
		poems = Poem.objects.all()
		serializer = PoemSerilizer(poems,many=True)
		return Response(serializer.data)

	def post(self,request,format=None):
		serializer = PoemSerilizer(data=request.data,many=True)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data,status=status.HTTP_201_CREATED)
		else:
			return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET','PUT','DELETE'])
def poem_detail(request,pk):
	try:
		poem = Poem.objects.get(pk=pk)
	except Poem.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method == 'GET':
		serializer = PoemSerilizer(poem)
		return Response(serializer.data)
	elif request.method == 'PUT':
		serializer = PoemSerilizer(poem,request.data)
		if serializer.is_valid():
			serializer.save()
		else:
			return Response(serializer.data)
	elif request.method == 'DELETE':
		poem.delete()
		return Response(status=status.HTTP_204_NO_CONTENT)

def modify(request):
	poem = Poem.objects.get(pk=1)
	poem.title = '1'
	poem.save()
	return render(request, 'todo_list.html')